<template>
    <div>
        <h1>测试webSocket通信</h1>
        <div>
            {{text}}
        </div>
    </div>
</template>

<script>
    export default {
        name: "WebSocket",
        data() {
            return {
                text: ""
            }
        },
        created() {
            //页面创建生命周期
            this.initWebSocket();
        },
        destroyed() {
            //销毁页面生命周期
            this.websocketclose();
        },
        methods: {
            initWebSocket() {
                // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
                this.websock = new WebSocket("ws://localhost:8080/websocket/DPS007");
                this.websock.onopen = this.websocketonopen;
                this.websock.onerror = this.websocketonerror;
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onclose = this.websocketclose;
            },
            websocketonopen() {
                console.log("WebSocket连接成功");
            },
            websocketonerror(e) {
                console.log("WebSocket连接发生错误");
            },
            websocketonmessage(e) {
                console.log(e.data);
                this.text = "something";
            },
            websocketclose(e) {
                console.log("connection closed (" + e.code + ")");
            },
        }
    }
</script>

<style scoped>

</style>